<template>
  <div class="referPlayer">
    <h3>运动员查询</h3>
    <div class="table">
      <div style="padding: 20px;">
        <el-row type="flex" :gutter="20" justify="space-between">
          <el-col :span="11">
            <sport2sportItem ref="sport2sportItem" search="search" title="教练员" :isCoach="true"
              :sportChangesportItemData="sportChangesportItemData" @selectDataChange='searchSelectDataChange' />
          </el-col>
          <el-col :span="5">
            <el-button-group class="flex">
              <el-select v-model="searchForm.playerStatusId" size="small" style="margin-left: 20px;" multiple collapse-tags filterable clearable placeholder="选择运动员状态">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_playerStatus" :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="searchForm.playerStatusId = Object.keys(dict_playerStatus)">全选</el-button>
            </el-button-group>
          </el-col>
          <el-col :span="5">
            <el-button-group class="flex">
              <el-select v-model="searchForm.age" size="small" multiple filterable collapse-tags clearable placeholder="选择年龄">
                <el-option :label="item+'岁'" :value="item" v-for="(item,index) in ageArr" :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="selectAgeAll">全选</el-button>
            </el-button-group>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.focusTypeId" size="small" style="float: right;" collapse-tags filterable clearable placeholder="选择集中类型">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_focus_type" :key="index"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row :gutter="20" type="flex" justify="space-between" style="margin-top: 20px;">
          <el-col :span="6" class="flex">
            <el-button type="success" size="medium" icon="el-icon-download" @click="exportAllDataEvent">导出</el-button>
            <el-button type="success" size="medium" icon="el-icon-printer" @click="printEvent">打印</el-button>
            <el-button type="success" size="medium" icon="el-icon-plus" @click="playerInsert">新增</el-button>
          </el-col>
          <el-col :span="6">
            <el-date-picker
            style="width: 80%;"
              size="medium"
              v-model="selectDate"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="-"
              start-placeholder="选择开始日期"
              end-placeholder="选择结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-col>
          <el-col :span="4">
              <el-checkbox size="medium" v-model="newPlayer" label="当前时间入校" border></el-checkbox>
          </el-col>
          <el-col :span="4" class="flex">
            <el-button type="success" size="medium" icon="el-icon-s-promotion" @click="searchSubmit" style="margin-right: 10px;">搜索</el-button>
            <el-button @click="clearTableFilter" size="medium" type="warning" icon="el-icon-refresh-right"> 清空</el-button>
          </el-col>
          <el-col :span="4">
            <vxe-input style="float: right;width: 100%" size="medium" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
          </el-col>
        </el-row>
      </div>
      <vxe-table resizable show-overflow border ref="empTable" max-height="700" keep-source border stripe highlight-hover-row highlight-current-row
       @sort-change="sortChange"
       :loading="loading" :data="playerData">
        <vxe-table-column field="name" title="姓名" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="idNo" width="160" title="身份证" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="genderName" title="性别" sortable :filters="[{label: '男', value: '男'}, {label: '女', value: '女'}]"></vxe-table-column>
        <vxe-table-column field="age" title="年龄" sortable sort-type="number" :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="joinDate" title="入队时间" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="leftDate" title="离队时间" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="playerStatus" title="运动员状态" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="focusType" title="集中类型" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="coachs" title="教练员" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="sportName" title="运动项目" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="memo" title="备注" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="" title="操作" width="150">
          <template #default="{ row }">
            <div class="">
              <el-tooltip class="item" effect="dark" content="档案管理" placement="top">
                <el-button @click="playerDetail(row)" size="medium"  type="success" icon="el-icon-setting" circle></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="档案打印" placement="top">
                <el-button @click="detailPrintModelShow(row)" size="medium" type="info" icon="el-icon-printer" circle></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="备注修改" placement="top">
                <el-button @click="editMemo(row)" size="medium" type="warning" icon="el-icon-edit" circle></el-button>
              </el-tooltip>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
        :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
        @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="editMemoShow" title="修改备注">
      <template #default>
        备注： <el-input v-model="currentMemo" size="small" style="width: 80%;"></el-input>
        <div style="height: 50px;text-align: center;line-height: 50px;">
          <el-button @click="updateMemo" type="success" size="small" icon="el-icon-s-promotion">保存</el-button>
          <el-button @click="editMemoShow = false" size="small" type="warning">取消</el-button>
        </div>
      </template>
    </vxe-modal>
    <vxe-modal v-model="printModal" title="定制您的打印" width="600px">
      <template #default>
        <div class="print print-top">
          <el-button @click="topClick(item,index)" type="success" v-for="item,index in printTopData" :key="index">{{dict_print[item]}}</el-button>
        </div>
        <div class="print print-bottom">
          <el-button @click="bottomClick(item,index)" type="infor" v-for="item,index in printbottomData" :key="index">{{dict_print[item]}}</el-button>
        </div>
        <div style="display: flex;justify-content: center;margin-top: 10px;">
          <el-button @click="refreshPrint" type="success" icon="el-icon-refresh">重置</el-button>
          <el-button @click="selectPrint" type="success" icon="el-icon-check">全选</el-button>
          <el-button @click="playerDetailPrint" type="success" v-loading.fullscreen.lock="fullscreenLoading" icon="el-icon-printer">打印</el-button>
          <el-button @click="clearPrint" type="warning">取消</el-button>
        </div>
      </template>
    </vxe-modal>
    <div style="visibility: hidden;overflow: hidden;height: 10px;">
      <playerDetailPrint ref="playerDetailPrint" :detailData="detailData" />
    </div>
  </div>
</template>

<script>
  import { player_select,getPid,player_selectBySearch,player_update,getDetail } from '@/api/person.js'
  import { player_status,focus_type,coach_by_org } from '@/api/dict.js'
  import sport2sportItem from "@/components/sport2sportItem/sport2sportItem.vue"
  import playerDetailPrint from '@/components/print/playerDetailPrint.vue'
  export default {
    components: {sport2sportItem,playerDetailPrint},
    data() {
      return {
        fullscreenLoading: false,
        pId: '',
        printTopData: [],
        printbottomData: ['player_basic','player_detail','family','player_sportResume','player_training','education','player_transport','player_schoolRoll','professionLevel','precis','player_takePartInMatch','cultureResult','monitor'],
        dict_print: {
          'player_basic': '基本信息',
          'player_detail': '详细信息',
          'family': '家庭成员',
          'education': '教育经历',
          'player_sportResume': '运动简历',
          'player_training': '集训情况',
          'player_transport': '输送情况',
          'player_schoolRoll': '学籍情况',
          'professionLevel': '运动等级',
          'player_takePartInMatch': '比赛成绩',
          'precis': '大纲考核',
          'cultureResult': '文化成绩',
          'monitor': '机能监控'
        },
        printModal: false,
        playerData: [],
        defaultPlayerData: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        dict_focus_type: {},
        dict_playerStatus: {},
        dict_coach: {},
        dict_idNo: {},
        filterName: '',
        age: '',
        sportId: '',
        sportItemId: '',
        sportItemData: [],
        professionTypeId: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        selectDate: '',
        sportChangesportItemData: {},
        searchForm: {
          sportId: '',
          sportItemId: '',
          coachId: '',
          focusTypeId: '',
          playerStatusId: '',
          age: '',
        },
        playerInfo: {},
        editMemoShow: false,
        currentMemo: '',
        currentRow: {},
        newPlayer: false,
        searchProps: [],
        detailData: {},
        ageArr: [],
        search: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getPlayer()
      })
    },
    watch: {
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      }
    },
    methods: {
      sortChange({ column, property, order, sortBy, sortList, $event }) {
        this.page.pageSize = this.defaultPlayerData.length
        this.findList()
        // this.$refs.empTable.sort(property, order)
      },
      customSortMethod({ data, sortList }){
        this.page.pageSize = this.defaultPlayerData.length
        // this.findList()
        data = this.defaultPlayerData
        const sortItem = sortList[0]
        // 取出第一个排序的列
        const { property, order } = sortItem
        let list = []
        if (order === 'asc' || order === 'desc') {
          // 例如：实现中英文混排，按照字母排序
          list = data.sort((a, b) => {

             let aname = a[property]
              let bname = b[property]
            if(typeof aname == 'number' && typeof bname == 'number'){
              if(!isNaN(aname) && !isNaN(aname) ){
                return aname - bname
              }else{
                if(isNaN(aname)){
                  return -1
                }
                if(isNaN(bname)){
                  return 1
                }
                return 0
              }
            }else{

              if(typeof aname =='string'){
                return aname.localeCompare(bname)
              }

              if(typeof bname =='string'){
                return !bname.localeCompare(aname)
              }
              return -1
            }
          })
        }
        if (order === 'desc') {
          list.reverse()
        }
        return list
      },
      updateMemo() {
        player_update({playerId:this.currentRow.playerId,memo:this.currentMemo}).then(res=>{
          if(res.code === 200){
            this.$message.success('保存成功')
            this.insertSuccess = true
            this.currentRow.memo = this.currentMemo
            this.editMemoShow = false
          }else{
            this.$message.error('保存失败')
          }
        })
      },
      editMemo(row){
        this.currentRow = row
        this.currentMemo = row.memo
        this.editMemoShow = true
      },
      searchSelectDataChange({
        sportId,
        sportItemId,
        person
      }) {
        this.searchForm.sportId = sportId
        this.searchForm.sportItemId = sportItemId
        this.searchForm.coachId = person
      },
      openFullScreen1() {
        setTimeout(() => {
        }, 2000);
      },
      detailPrintModelShow(row) {
        this.pId = row.pid
        // this.refreshPrint()
        this.playerInfo = row
        this.printModal = true
      },
      playerDetailPrint() {
        if(this.printTopData.length != 0){
          this.fullscreenLoading = true;
          let data = {
            pId: this.pId,
            data: {personInfoPrintSpec: this.printTopData.join(',')}
          }
          this.detailData = {}
          getDetail(data).then(res=>{
            if(res.code === 200) {
              this.detailData = res.data
              let resValue = []
              for(let key in this.detailData) {
                let item = this.detailData[key]
                if(item){
                  resValue.push(...Object.values(item))
                }
              }
              if(resValue.length!=0){
                setTimeout(()=>{
                  this.$refs.playerDetailPrint.tablePrint()
                  this.fullscreenLoading = false;
                },200)
              }else{
                this.$message.warning('没有可用数据！')
                this.fullscreenLoading = false;
              }
            }else{
              this.$message.error('打印数据有误！')
              this.fullscreenLoading = false;
            }
          })
        }else{
          this.$message.warning('至少选择一项打印！')
        }
      },
      refreshPrint(){
        this.printbottomData = ['player_basic','player_detail','family','player_sportResume','player_training','education','player_transport','player_schoolRoll','professionLevel','precis','player_takePartInMatch','cultureResult','monitor']
        this.printTopData = []
      },
      selectPrint(){
        this.printbottomData = []
        this.printTopData = ['player_basic','player_detail','family','player_sportResume','player_training','education','player_transport','player_schoolRoll','professionLevel','precis','player_takePartInMatch','cultureResult','monitor']
      },
      clearPrint(){
        // this.refreshPrint()
        this.printModal = false
      },
      topClick(item,index){
        this.printTopData.splice(index,1)
        this.printbottomData.push(item)
      },
      bottomClick(item,index){
        this.printbottomData.splice(index,1)
        this.printTopData.push(item)
      },
      playerDetail(row) {
        window.sessionStorage.setItem('pId',row.pid)
        // this.$router.push('/playerDetail')
        const { href } = this.$router.resolve({path:'/playerDetail'});
        window.open(href, '_blank');
      },
      playerInsert() {
        window.sessionStorage.setItem('isPlayer',1)
        this.$router.push('/personInsert')
      },
      printEvent() {
        let topHtml = '<h2>运动员名单</h2>'
        this.searchEvent()
        setTimeout(()=>{
          this.$refs.empTable.print({
              sheetName: '运动员名单',
              beforePrintMethod: ({content}) => {
                  return topHtml + content
              }
          })
        },1000)
      },
      exportAllDataEvent() {
        this.loading = true
        setTimeout(() => {
          this.$refs.empTable.exportData({
            filename: '运动员名单',
            isHeader: true,
            isFooter: true,
            data: this.search?this.playerData:this.defaultPlayerData
          })
          this.loading = false
        }, 100)
      },
      clearTableFilter() {
        this.searchForm = {
          sportId: '',
          sportItemId: '',
          coachId: '',
          focusTypeId: '',
          playerStatusId: '',
          age: '',
        },
        this.newPlayer = false
        this.selectDate = ''
        this.sportChangesportItemData = {}
        this.$refs.empTable.clearFilter()
        this.getPlayer()
      },
      searchSubmit() {
        let data = {}
        if(this.searchForm.playerStatusId.length != 0) {
          data.playerStatusIdStr = this.searchForm.playerStatusId.join(',')
        }
        if(this.searchForm.age.length != 0) {
          data.ageStr = this.searchForm.age.join(',')
        }
        if(this.searchForm.sportId) {
          data.sportId = this.searchForm.sportId
        }
        if(this.searchForm.sportItemId) {
          data.sportItemId = this.searchForm.sportItemId
        }
        if(this.searchForm.coachId) {
          data.coachId = this.searchForm.coachId
        }
        if(this.searchForm.focusTypeId) {
          data.focusTypeId = this.searchForm.focusTypeId
        }
        if(this.selectDate) {
          data.startDate = this.selectDate[0] + ' 00:00:00'
          data.endDate = this.selectDate[1] + ' 00:00:00'
        }
        data.newPlayer = this.newPlayer
        player_selectBySearch(data).then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            window.localStorage.setItem('playerList',JSON.stringify(res.data))
            this.init_data(res.data)
          }else{
            this.defaultPlayerData = []
          }
        }).then(()=>{
            this.findList()
          })
      },
      sportChange(option) {
        this.sportItemData = ''
        this.sportItemId = ''
        sport_item_by_sportId({sportId:option}).then(res=>{
          if(res.code === 200){
            this.sportItemData = res.data
          }
        })
      },
      selectAgeAll() {
        this.searchForm.age = this.ageArr
      },
      customStringFilterMethod({ option, row, column}) {
        if (option.data) {
          return this.$XEUtils.toValueString(row[column.property]).toLowerCase().indexOf(option.data) > -1
        }
      },
      filterEvent(option) {
        const xTable = this.$refs.empTable
        // 设置为选中状态
        option.checked = true
        // 修改条件之后，需要手动调用 updateData 处理表格数据
        xTable.updateData()
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultPlayerData.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.playerData = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.playerData.length,
            totalResult: this.playerData.length
          }
          this.search = true
        } else {
          this.playerData = this.defaultPlayerData
        }
      },
      getPlayer() {
        this.loading = true
        let dict_idNo = {}
        getPid().then(res=>{
          if(res.code === 200) {
            res.data.forEach(item=>{
              dict_idNo[item.pid] = item.idNo
            })
            this.dict_idNo = dict_idNo
          }
        }).then(()=>{
          player_select().then(res=>{
            if(res.code === 200 && res.data.length!=0) {
              this.init_data(res.data)
            }else{
              this.defaultPlayerData = []
            }
          }).then(()=>{
            this.findList()
          })
        })
      },
      init_data(data) {
        if(data.length==0) return
        let dict_gender = {1:'男',2:'女'}
        data.forEach(item=>{
          item.idNo = this.dict_idNo[item.pid]
          item.genderName = dict_gender[item.genderId]
          item.age = this.$moment().get('year') - this.$moment(item.birthday).get('year')
          if(item.joinDate){
            item.joinDate = this.$moment(item.joinDate).format('YYYY-MM-DD')
          }
          if(item.leftDate){
            item.leftDate = this.$moment(item.leftDate).format('YYYY-MM-DD')
          }
          item.playerStatus = this.dict_playerStatus[item.playerStatusId]
          item.focusType = this.dict_focus_type[item.focusTypeId]
          let coachArr = item.coachIdStr.split(',')
          let arr = []
          coachArr.forEach(coach=>{
            arr.push(this.dict_coach[coach])
          })
          item.coachs = arr.join(',')
        })
        this.searchProps = Object.keys(data[0])
        this.defaultPlayerData = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          for(let i=3;i<=50;i++){
            this.ageArr.push(i)
          }
          player_status().then(res=>{
            this.dict_playerStatus = res
          })
          focus_type().then(res=>{
            this.dict_focus_type = res
          })
          coach_by_org().then(res=>{
            this.dict_coach = res
            resolve()
          })
        })
      },
      handlePageChange({currentPage,pageSize}) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        if(!this.search){
          this.page.pageSize = this.defaultPlayerData.length
          this.findList()
        }else{
          this.page.pageSize = this.playerData.length
        }
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultPlayerData.length
          this.playerData = this.defaultPlayerData.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 500)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .referPlayer{
    .table{
      width: 100%;
      height: 100%;
      background-color: #fff;
      padding: 0 10px;

      .operate{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;


        .vxe-button+.vxe-button, .vxe-button+.vxe-button--dropdown, .vxe-input+.vxe-button, .vxe-input+.vxe-button--dropdown{
          margin-left: 0;
        }
        .vxe-button{
          color: #0DA883;
          &:hover{
            color: #81cb94;
            text-decoration: underline;
          }
        }
      }
    }
    .print{
      width: 100%;
      height: 200px;
      border: 1px solid #0DA883;
      padding: 10px;
      display: flex;
      align-items: flex-start;
      flex-wrap: wrap;

      .el-button{
        margin: 0 5px;
      }
    }

    .print-top{
      margin-bottom: 10px;
    }
    .flex{
      display: flex;
    }
  }
</style>
